﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
using Pb;
using UnityEngine.SceneManagement;

public class PDKGame : Game {
    EginUser user = EginUser.Instance;
    EginPDK pdk = EginPDK.Instance;
    //玩家
    public List<PDKUser> pdkUsers;
    public GamePDKPanel gamePDKPanel;

    private PDKCardsControl pdkCardsControl;

    //房间号
    public List<UISprite> roomIDSprits;
    public GameObject roomObj;
    public GameObject baseScoreObj;
    public UILabel baseScoreLabel;
    public UISprite roomLevelSprite;

    //root
    public GameObject Root;


    //音效
    public List<AudioClip> cardsSingleMen;
    public List<AudioClip> cardsSingleWomen;
    public List<AudioClip> cardsTwinMen;
    public List<AudioClip> cardsTwinWomen;
    public List<AudioClip> muchThreeMen;
    public List<AudioClip> muchThreeWomen;
    public List<AudioClip> CommonMen;
    public List<AudioClip> CommonWomen;
    public List<AudioClip> effectBg;
    //音效
    public List<AudioClip> textMen;
    public List<AudioClip> textWomen;

    //控制报单音效只出现一次
    private int num = 0;
    private int num1 = 0;
    private int num2 = 0;


    ////暂时存进内存
    //private pdkCardsControl pdkCardsControl;
    //private GameObject LastThreeCards;
    //private GameObject CallScore;
    //private GameObject LastThreeCardsShow;
    //private GameObject Time;

    private string[] pdkText = {
        "别吵了，别吵了，专心玩游戏吧！",
        "和你合作真是太愉快了！",
        "快点啊，等的我花都谢了！",
        "你这么牛X你家里人知道吗？",
        "土豪我们做朋友吧",
        "看我通杀全场！",
        "怎么又掉线了，网络也太差了吧！"
    };


    void Awake()
    {
        base.StartGameSocket();
        SocketManager.Instance.socketListener = this;       
    }

    void Start()
    {
        //加载玩家
        LoadUser(); 
        //如果是好友场就显示房间号
        if (user.ControlScene == 1)
        {
            string tempRoomID = pdk.roomId.ToString();
            for (int i = 0; i < 6; i++)
            {
                string str = tempRoomID.Substring(0, 1);
                tempRoomID = tempRoomID.Remove(0, 1);
                roomIDSprits[i].spriteName = str;
            }
            roomObj.SetActive(true);
            baseScoreObj.SetActive(false);
        }
        else
        {
            baseScoreObj.SetActive(true);
            roomObj.SetActive(false);
            baseScoreLabel.text = user.ReturnRelCoinForBrief(pdk.baseScore);
            if(pdk.baseScore == 10000){
                pdk.typeId = 1;
            }
            else if (pdk.baseScore == 50000)
            {
                pdk.typeId = 2;
            }
            else if (pdk.baseScore == 100000)
            {
                pdk.typeId = 3;
            }
            roomLevelSprite.spriteName = "text" + pdk.typeId;
        }
        //重连
        if (pdk.isReconnect == true)
        {
            pdk.isReconnect = false;
            PDKReconnect();
        }       
    }

    public override void SocketReceiveMessage(byte[] data)
    {
        base.SocketReceiveMessage(data);
        byte[] dataLength = data.Skip(0).Take(2).ToArray();
        byte[] dataId = data.Skip(2).Take(4).ToArray();
        byte[] dataConcent = data.Skip(data.Length - (data.Length - 4)).ToArray();
        int TempMsgID = ProtoDataToMsg.Byte2ushort(dataId);


        #region 斗地主玩家加入离开房间返回  准备消息
        if (TempMsgID == MsgId.RoomUserInfoBroadcast)
        {
            Pb.RoomUserInfoBroadcast newpb = Pb.RoomUserInfoBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            if (newpb.UserInfo.SeatStatus == SEAT_STATUS.Sit)
            {
                //加入房间
                user.gameUserInfoList.Add(newpb.UserInfo);
                int tempIndex = pdk.returnOtherSeatIndex(newpb.UserInfo.SeatId);
                pdkUsers[tempIndex].gameObject.SetActive(true);
                pdkUsers[tempIndex].seatId = newpb.UserInfo.SeatId;
                pdkUsers[tempIndex].sex = newpb.UserInfo.Sex;
                if(newpb.UserInfo.AvatarUrl != ""){
                    WXAvatarManager._instance.GetWxAvatar(newpb.UserInfo.Uid,pdkUsers[tempIndex].wxAvatar,newpb.UserInfo.AvatarUrl);
                    pdkUsers[tempIndex].wxAvatar.gameObject.SetActive(true);
                }
                else
                {
                    pdkUsers[tempIndex].avatar.spriteName = newpb.UserInfo.AvatarId.ToString();
                }                
                //StartCoroutine(GetWWWFace(pdkUsers[tempIndex].wxAvatar,newpb.UserInfo.AvatarUrl));
                if (user.ControlScene == 1)
                {
                    //如果是房卡模式显示分 金币模式还是显示金币
                    if (pdk.isCardRoom == true)
                    {
                        pdkUsers[tempIndex].markObj.SetActive(true);
                        string str = user.ReturnMoney(newpb.UserInfo.Score);
                        pdkUsers[tempIndex].coinLabel.text = str;
                    }
                    else
                    {
                        pdkUsers[tempIndex].markObj.SetActive(false);
                        string str = user.ReturnMoney(newpb.UserInfo.BagCoinCount);
                        pdkUsers[tempIndex].coinLabel.text = str;
                    }
                }
                else
                {
                    string str = user.ReturnMoney(newpb.UserInfo.BagCoinCount);
                    pdkUsers[tempIndex].coinLabel.text = str;
                }

            }
            else if (newpb.UserInfo.SeatStatus == SEAT_STATUS.Leave)
            {
               
                if (pdk.roomStatus != ROOM_STATUS.Gaming)
                {
                    //离开房间
                    for (int i = 0; i < user.gameUserInfoList.Count; i++)
                    {
                        if (newpb.UserInfo.SeatId == user.gameUserInfoList[i].SeatId)
                        {
                            Debug.Log("有人离开了");
                            user.gameUserInfoList.RemoveAt(i);
                            int tempIndex = pdk.returnOtherSeatIndex(newpb.UserInfo.SeatId);
                            pdkUsers[tempIndex].gameObject.SetActive(false);
                            pdkUsers[tempIndex].InitPlayer();
                            pdkUsers[tempIndex].wxAvatar.gameObject.SetActive(false);
                            break;
                        }
                    }
                }
            }
            //准备广播
            else if (newpb.UserInfo.SeatStatus == SEAT_STATUS.Ready)
            {
                Debug.Log("已准备");
                Debug.Log("游戏开始时房间状态：" + pdk.roomStatus);
                int tempIndex = pdk.returnOtherSeatIndex(newpb.UserInfo.SeatId);
                if (pdk.roomStatus != ROOM_STATUS.Gaming)
                {
                    pdkUsers[tempIndex].ReadyStatus.gameObject.SetActive(true);
                }
                if (pdk.seatId == newpb.UserInfo.SeatId)
                {
                    gamePDKPanel.PrepareGreenBtn.SetActive(false);
                    gamePDKPanel.ChangeTableOrangeBtn.SetActive(false);
                    gamePDKPanel.FriendRoomObj.SetActive(false);
                }    
            }
        }
        else if (TempMsgID == MsgId.RoomReadyResponse)
        {
            Pb.RoomReadyResponse newpb = Pb.RoomReadyResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            //pdkUsers[0].ReadyStatus.gameObject.SetActive(true);
        }
        //离开房间
        else if (TempMsgID == MsgId.RoomLeaveResponse)
        {
            Pb.RoomLeaveResponse newpb = Pb.RoomLeaveResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            if (newpb.Status == STATUS.Success)
            {
                EginUser.Instance.gameUserInfoList.Clear();
                SceneManager.LoadScene(ScenePath.Hall);
                //Application.LoadLevelAsync(ScenePath.Gamepdk);

            }
            else
            {
                user.logMsg = newpb.Msg;
                GameObject Set = NGUITools.AddChild(Root, (GameObject)(Resources.Load("LogMsg")));
            }
        }
        else if (TempMsgID == MsgId.RoomDismissBroadcast)
        {
            Pb.RoomDismissBroadcast newpb = Pb.RoomDismissBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            EginUser.Instance.gameUserInfoList.Clear();
            SceneManager.LoadScene(ScenePath.Hall);
        }

        #endregion

        #region 跑的快Game消息
        else if(TempMsgID == MsgId.RoomReadyResponse){
            //准备响应
            pdkUsers[0].ReadyStatus.gameObject.SetActive(true);
            gamePDKPanel.PrepareGreenBtn.SetActive(false);
            gamePDKPanel.ChangeTableOrangeBtn.SetActive(false);
            gamePDKPanel.FriendRoomObj.SetActive(false);
        }
        else if (TempMsgID == MsgId.RunRoomBeginNotification)
        {
            //游戏开始
            Pb.RunRoomBeginNotification newpb = Pb.RunRoomBeginNotification.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            pdk.roomStatus = ROOM_STATUS.Gaming;
            pdk.currentRound = newpb.CurrentRound;
            pdk.bankerSid = newpb.BankerSid;
            pdk.seatId = newpb.SeatId;
            Debug.Log("newpb.BankerSid = " + newpb.BankerSid);
            //关闭ready状态
            for (int i = 0; i < pdkUsers.Count;i++ )
            {
                pdkUsers[i].ReadyStatus.gameObject.SetActive(false);
                //重置出牌的时间
                pdkUsers[i].clock.GetComponent<PDKTimeControl>().timeCount = 26;
            }
            //生成cards
            List<int> ownCards = newpb.CardList.ToList();
            GameObject pdkCards = NGUITools.AddChild(Root, (GameObject)(Resources.Load(GamePDKPrefabPath.PDKCards)));
            pdkCardsControl = pdkCards.GetComponent<PDKCardsControl>();
            //初始展示自己的手牌
            pdkCardsControl.StartShowCards(ownCards);
            //播放游戏开始背景
            SoundModel.PlayEffectBg(effectBg[2]);
            StartCoroutine(ShowFirstOutCard(newpb));    
        }
        else if (TempMsgID == MsgId.RunPlayResponse)
        {
            Pb.RunPlayResponse newpb = Pb.RunPlayResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            if(newpb.Status == STATUS.Success){

            }
            else
            {
                user.logMsg = newpb.Msg;
                GameObject Set = NGUITools.AddChild(Root, (GameObject)(Resources.Load("LogMsg")));
            }
        }
        else if (TempMsgID == MsgId.RunPlayBroadcast)
        {
            Pb.RunPlayBroadcast newpb = Pb.RunPlayBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            Debug.Log("当前的牌型是" + newpb.PokerType);
            //隐藏当前出牌的人的时间
            int tempIndex = pdk.returnOtherSeatIndex(newpb.SeatId);
            pdkUsers[tempIndex].clock.SetActive(false);

            if (newpb.TurnDetail != null)
            {
                pdk.nextSid = newpb.TurnDetail.SeatId;
            }
            else
            {
                pdk.nextSid = 0;
            }
            
            //得到各个位置的玩家性别
            for (int i = 0; i < user.gameUserInfoList.Count;i++ )
            {
                int userIndex = pdk.returnOtherSeatIndex(user.gameUserInfoList[i].SeatId);
                pdkUsers[userIndex].sex = user.gameUserInfoList[i].Sex;
            }

            if (newpb.PokerType != POKER_TYPE.Pass)
            {
                pdkCardsControl.lastPokerType = newpb.PokerType;
                pdkCardsControl.lastSeatId = newpb.SeatId;
                pdkCardsControl.lastOutCards = newpb.CardList.ToList();
                //显示过牌UI
                //显示剩余牌张数
                pdkCardsControl.OtherCardRemainderShow(-newpb.CardList.ToList().Count, newpb.SeatId);
                //判断是否显示报单图标                
                if(pdkCardsControl.ownRemainder == 1){
                    Debug.Log("pdkCardsControl.ownRemainder = " + pdkCardsControl.ownRemainder);
                    pdkUsers[0].BaoDan.SetActive(true);                   
                    num++;
                    //播放报单背景音效
                    //SoundModel.PlayEffectBg(effectBg[1]);
                    if(num == 1){
                        //播放报单声音
                        if (pdkUsers[0].sex == SEX.Male)
                        {
                            SoundModel.PlaySound(CommonMen[8]);
                        }
                        else
                        {
                            SoundModel.PlaySound(CommonWomen[8]);
                        }
                    }
                    
                }
                if (pdkCardsControl.leftRemainder == 1)
                {
                    pdkUsers[2].BaoDan.SetActive(true);                    
                    num1++;
                    //播放报单背景音效
                    //SoundModel.PlayEffectBg(effectBg[1]);
                    if (num1 == 1)
                    {
                        //播放报单声音
                        if (pdkUsers[0].sex == SEX.Male)
                        {
                            SoundModel.PlaySound(CommonMen[8]);
                        }
                        else
                        {
                            SoundModel.PlaySound(CommonWomen[8]);
                        }
                    }
                }
                if (pdkCardsControl.rightRemainder == 1)
                {
                    pdkUsers[1].BaoDan.SetActive(true);
                    num2++;
                    //播放报单背景音效
                    //SoundModel.PlayEffectBg(effectBg[1]);
                    if (num2 == 1)
                    {
                        //播放报单声音
                        if (pdkUsers[0].sex == SEX.Male)
                        {
                            SoundModel.PlaySound(CommonMen[8]);
                        }
                        else
                        {
                            SoundModel.PlaySound(CommonWomen[8]);
                        }
                    }
                }
            }
            
            //把出的牌显示出来或者显示要不起
            pdkCardsControl.ShowPlayerOutCard(newpb.CardList.ToList(), newpb.SeatId, newpb.PokerType, pdk.nextSid);  
    
            //把出的牌隐藏掉 重新显示手牌 把出牌的按钮初始化
            if (newpb.SeatId == pdk.seatId)
            {
                pdkCardsControl.RemoveOutCards(newpb.CardList.ToList());
                //隐藏出牌提示按钮
                pdkCardsControl.InitBtn();               
                //显示取消托管按钮
                if (newpb.IsRobot)
                {
                    pdkCardsControl.CancelAuto.SetActive(true);
                }
            }            
                     
            if(newpb.TurnDetail != null){
                //判断下一个人的出牌情况
                int nextIndex = pdk.returnOtherSeatIndex(newpb.TurnDetail.SeatId);
                Debug.Log("newpb.TurnDetail.IsPlay = " + newpb.TurnDetail.IsPlay);
                if (newpb.TurnDetail.IsPlay == true)
                {
                    //该出牌的显示出牌按钮
                    if (newpb.TurnDetail.SeatId == pdk.seatId)
                    {
                        //玩家能出牌就显示出牌按钮 不能出牌就发送空的出牌列表
                        pdkCardsControl.ShowOutCardButton();
                    }
                    //显示下一个出牌的人的时间
                    //int tempIndex1 = pdk.returnOtherSeatIndex(newpb.TurnDetail.SeatId);
                    pdkUsers[nextIndex].clock.SetActive(true);
                    pdkUsers[nextIndex].clock.GetComponent<PDKTimeControl>().timeCount = 26;
                }
                else
                {
                    if (pdk.nextSid == pdk.seatId)
                    {
                        StartCoroutine(ShowCantPut());
                    }
                }
            }            
                                            
            //出牌音效
            int z = 0;
            if (newpb.CardList.Count > 0)
            {
                z = newpb.CardList[0];
            }

            PlaySound(newpb.PokerType, z, newpb.SeatId);

            //显示托管状态
            if (newpb.IsRobot)
            {
                int tempIndex2 = pdk.returnOtherSeatIndex(newpb.SeatId);
                pdkUsers[tempIndex2].AutoStatus.SetActive(true);
            }

        }
        //游戏结束广播
        else if (TempMsgID == MsgId.RunGameOverBroadcast)
        {
            Pb.RunGameOverBroadcast newpb = Pb.RunGameOverBroadcast.Parser.ParseFrom(dataConcent);            
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            
            for (int i = 0; i < pdkUsers.Count;i++ )
            {   //隐藏时钟  托管状态 报单图标
                pdkUsers[i].clock.SetActive(false);
                pdkUsers[i].AutoStatus.SetActive(false);
                pdkUsers[i].BaoDan.SetActive(false);
            }            
            //隐藏取消托管按钮
            if (pdkCardsControl != null)
            {
                pdkCardsControl.CancelAuto.SetActive(false);
            }
            Debug.Log("游戏结束时用户金币 = " + newpb.CoinCount);            
            //user.coinCount = newpb.CoinCount.ToString();
            pdk.roomStatus = newpb.RoomStatus;
            Debug.Log("游戏结束时房间状态：" + newpb.RoomStatus);
            List<GameOverUserInfo> gameOverUserInfo = newpb.UserList.ToList();
                     
            if (user.ControlScene == 1)
            {
                for (int i = 0; i < gameOverUserInfo.Count; i++)
                {
                    int tempIndex = pdk.returnOtherSeatIndex(gameOverUserInfo[i].SeatId);
                    //如果是房卡模式显示分 金币模式还是显示金币
                    if (pdk.isCardRoom == true)
                    {
                        Debug.Log("游戏结束 房卡模式");                       
                        user.gameUserInfoList[i].Score += gameOverUserInfo[i].RoundScore;
                        string str = user.ReturnMoney(user.gameUserInfoList[i].Score);
                        pdkUsers[tempIndex].coinLabel.text = str;
                    }
                    else
                    {
                        Debug.Log("游戏结束 金币模式");
                        //游戏结束时玩家金币数
                        Debug.Log("游戏结束时金币数：" + gameOverUserInfo[i].BagCoinCount);
                        string str = user.ReturnMoney(gameOverUserInfo[i].BagCoinCount);
                        pdkUsers[tempIndex].coinLabel.text = str;
                        if (pdk.seatId == gameOverUserInfo[i].SeatId)
                        {
                            user.coinCount = gameOverUserInfo[i].BagCoinCount.ToString();
                        }
                    }

                }
            }
            else
            {
                for (int i = 0; i < gameOverUserInfo.Count; i++)
                {
                    Debug.Log("gameOverUserInfo[i].RoundScore = " + gameOverUserInfo[i].RoundScore);
                    int tempIndex = pdk.returnOtherSeatIndex(gameOverUserInfo[i].SeatId);
                    user.gameUserInfoList[i].BagCoinCount += gameOverUserInfo[i].RoundScore;
                    //游戏结束时玩家金币数
                    Debug.Log("游戏结束时金币数：" + gameOverUserInfo[i].BagCoinCount);
                    string str = user.ReturnMoney(gameOverUserInfo[i].BagCoinCount);                    
                    pdkUsers[tempIndex].coinLabel.text = str;
                    if(pdk.seatId == gameOverUserInfo[i].SeatId){
                        user.coinCount = gameOverUserInfo[i].BagCoinCount.ToString();
                    }
                }
            }
            
            //加载游戏结束界面
            GameObject GameOver = NGUITools.AddChild(Root, (GameObject)(Resources.Load(GamePDKPrefabPath.GameOverPanel)));
            PDKGameOver pdkGameOver = GameOver.GetComponent<PDKGameOver>();
            pdkGameOver.gameOverUserInfo = newpb.UserList.ToList();
            pdkGameOver.GameoverEvent(newpb.NextRound, gameOverUserInfo);
            pdkGameOver.nextover1 = newpb.NextRound;
            pdkGameOver.newpb = newpb;

        }
         //换桌
        else if (TempMsgID == MsgId.RunChangeTableResponse)
        {
            Pb.RunChangeTableResponse newpb = Pb.RunChangeTableResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            if (newpb.Status == STATUS.Success)
            {
                //玩家初始化
                for (int i = 0; i < pdkUsers.Count;i++ )
                {
                    pdkUsers[i].InitPlayer();
                }
                user.gameUserInfoList.Clear();
                user.gameUserInfoList = newpb.UserInfoList.ToList();
                pdk.seatId = newpb.SeatId;
                LoadUser();
            }
            else
            {
                user.logMsg = newpb.Msg;
                GameObject Set = NGUITools.AddChild(Root, (GameObject)(Resources.Load("LogMsg")));
            }
        }
       
        #endregion
        #region 文字表情聊天
        else if (TempMsgID == MsgId.RoomChatBroadcast)
        {
            Pb.RoomChatBroadcast newpb = Pb.RoomChatBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            StartCoroutine(TextFaceChat(newpb));
        }
        else if (TempMsgID == MsgId.UserTurnOnRobotResponse)
        {

            Pb.UserTurnOnRobotResponse newpb = Pb.UserTurnOnRobotResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            if(newpb.Status == STATUS.Success){
                Debug.Log("托管响应");
                pdkUsers[0].AutoStatus.SetActive(true);
                pdkCardsControl.CancelAuto.SetActive(true);
                gamePDKPanel.LeaveAndDelegate.SetActive(false);
                gamePDKPanel.HideSpriteBtn.SetActive(false);
                gamePDKPanel.ShowSpriteBtn.SetActive(true);
            }
            else
            {
                user.logMsg = newpb.Msg;
                GameObject obj = NGUITools.AddChild(Root,(GameObject)Resources.Load("LogMsg"));
            }
        }
        else if (TempMsgID == MsgId.UserTurnOnRobotBroadcast)
        {
            Pb.UserTurnOnRobotBroadcast newpb = Pb.UserTurnOnRobotBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            int tempIndex = pdk.returnOtherSeatIndex(newpb.SeatId);
            Debug.Log("tempIndex = " + tempIndex);
            pdkUsers[tempIndex].AutoStatus.SetActive(true);
        }
        #endregion  
        else if (TempMsgID == MsgId.UserCancelRobotResponse)
        {
            Pb.UserCancelRobotResponse newpb = Pb.UserCancelRobotResponse.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            pdkUsers[0].AutoStatus.SetActive(false);
            pdkCardsControl.CancelAuto.SetActive(false);
        }
        //取消托管
        else if (TempMsgID == MsgId.UserCancelRobotBroadcast)
        {
            Pb.UserCancelRobotBroadcast newpb = Pb.UserCancelRobotBroadcast.Parser.ParseFrom(dataConcent);
            Debug.Log("消息ID" + TempMsgID + "消息内容" + newpb);
            int tempIndex = pdk.returnOtherSeatIndex(newpb.SeatId);
            pdkUsers[tempIndex].AutoStatus.SetActive(false);
            if (pdk.seatId == newpb.SeatId)
            {
                pdkCardsControl.CancelAuto.SetActive(false);
            }
        }
         //网络异常
        else if (TempMsgID == MsgId.NetWorkAbnormalMessage)
        {
            GameObject NetWorkAbnormal = NGUITools.AddChild(GameObject.Find("UI Root"), (GameObject)(Resources.Load("NetWorkAbnormal")));
        }
    }


    /// <summary>
    /// 进入房间 加载用户信息
    /// </summary>
    void LoadUser()
    {
        Debug.Log("user.gameUserInfoList.Count = " + user.gameUserInfoList.Count);
        pdk.SortSeatId();
        for (int i = 0; i < user.gameUserInfoList.Count; i++)
        {
            int tempIndex = pdk.returnOtherSeatIndex(user.gameUserInfoList[i].SeatId);
            pdkUsers[tempIndex].gameObject.SetActive(true);
            pdkUsers[tempIndex].seatId = user.gameUserInfoList[i].SeatId;
            pdkUsers[tempIndex].sex = user.gameUserInfoList[i].Sex;

            if(user.gameUserInfoList[i].AvatarUrl != ""){
                WXAvatarManager._instance.GetWxAvatar(user.gameUserInfoList[i].Uid, pdkUsers[tempIndex].wxAvatar, user.gameUserInfoList[i].AvatarUrl);
                pdkUsers[tempIndex].wxAvatar.gameObject.SetActive(true);
            }
            else
            {
                pdkUsers[tempIndex].avatar.spriteName = user.gameUserInfoList[i].AvatarId.ToString();
            }
                                           
            //pdkUsers[tempIndex].username.text = user.gameUserInfoList[i].Nickname;
                       
            if (user.ControlScene == 1)
            {                           
                //如果是房卡模式显示分 金币模式还是显示金币
                if(pdk.isCardRoom == true){
                    Debug.Log("房卡模式");
                    pdkUsers[tempIndex].markObj.SetActive(true);
                    string str = user.ReturnMoney(user.gameUserInfoList[i].Score);
                    pdkUsers[tempIndex].coinLabel.text = str;   
                }
                else
                {
                    Debug.Log("金币模式");
                    pdkUsers[tempIndex].markObj.SetActive(false);
                    string str = user.ReturnMoney(user.gameUserInfoList[i].BagCoinCount);
                    pdkUsers[tempIndex].coinLabel.text = str;   
                }
                //显示准备和邀请按钮               
                gamePDKPanel.PrepareGreenBtn.SetActive(true);
                gamePDKPanel.FriendRoomObj.SetActive(true);
            }
            else
            {
                Debug.Log(user.gameUserInfoList[i].Nickname + "  " + user.gameUserInfoList[i].BagCoinCount);
                string str = user.ReturnMoney(user.gameUserInfoList[i].BagCoinCount);
                pdkUsers[tempIndex].coinLabel.text = str;
                //显示准备和换桌按钮
                gamePDKPanel.PrepareGreenBtn.SetActive(true);
                gamePDKPanel.ChangeTableOrangeBtn.SetActive(true);
            }
            
            if (user.gameUserInfoList[i].SeatStatus == SEAT_STATUS.Ready)
            {
                pdkUsers[tempIndex].ReadyStatus.gameObject.SetActive(true);
                
            }
        }
    }
  

    /// <summary>
    /// 文字表情聊天   
    /// </summary>
    /// <param name="newpb"></param>
    /// <returns></returns>  
    IEnumerator TextFaceChat(RoomChatBroadcast newpb)
    {
        int tempIndex = 0;
        for (int i = 0; i < user.gameUserInfoList.Count; i++)
        {
            if (newpb.FromUid == user.gameUserInfoList[i].Uid)
            {
                int tempSeatid = user.gameUserInfoList[i].SeatId;
                tempIndex = pdk.returnOtherSeatIndex(tempSeatid);
                if (newpb.MsgType == RoomChatType.TextId)
                {
                    pdkUsers[tempIndex].textObj.SetActive(true);
                    pdkUsers[tempIndex].text.text = pdkText[int.Parse(newpb.Content) - 1];
                    if (user.gameUserInfoList[i].Sex == SEX.Male)
                    {
                        SoundModel.PlaySound(textMen[int.Parse(newpb.Content) - 1]);
                    }
                    else
                    {
                        SoundModel.PlaySound(textWomen[int.Parse(newpb.Content) - 1]);
                    }
                }
                else if (newpb.MsgType == RoomChatType.MovieClip)
                {
                    pdkUsers[tempIndex].face.gameObject.SetActive(true);
                    pdkUsers[tempIndex].face.spriteName = newpb.Content;
                    Debug.Log("表情名字是：" + newpb.Content);
                }

            }
        }
        yield return new WaitForSeconds(2.5f);
        pdkUsers[tempIndex].textObj.SetActive(false);
        pdkUsers[tempIndex].face.gameObject.SetActive(false);
    }

    /// <summary>
    /// 发送要不起
    /// </summary>
    /// <returns></returns>
    IEnumerator ShowCantPut()
    {       
        pdkUsers[0].clock.SetActive(true);
        pdkUsers[0].clock.GetComponent<PDKTimeControl>().timeCount = 26;
        yield return new WaitForSeconds(1f);
        RunPlayRequest lg = new Pb.RunPlayRequest { };
        SocketManager socketManager = SocketManager.Instance;
        socketManager.SendProtobuf1(lg, MsgId.RunPlayRequest);
    }


    #region 重连
    /// <summary>
    /// 跑得快重连
    /// </summary>
    void PDKReconnect()
    {
        RunReconnectRoomResponse newpb = pdk.runReconnectRoomResponse;
        Debug.Log("重连消息：" + "消息内容" + newpb);

        pdk.createrUid = newpb.RoomInfo.CreaterUid;
        //pdk.bankerSid = newpb.BankerSid;
        pdk.roomId = newpb.RoomInfo.RoomId;
        pdk.currentRound = newpb.RoomInfo.CurrentRound;
        pdk.baseScore = newpb.RoomInfo.BaseScore;
        pdk.totalRound = newpb.RoomInfo.TotalRound;
        pdk.roomStatus = newpb.RoomInfo.RoomStatus;
        user.gameUserInfoList = newpb.UserInfoList.ToList();
    
        pdk.SortSeatId();
        //LoadUser();

        if(newpb.Status == STATUS.Success){
            //加载准备状态
            if (newpb.RoomInfo.RoomStatus != ROOM_STATUS.Gaming)
            {
                for (int i = 0; i < user.gameUserInfoList.Count; i++)
                {
                    if(pdk.seatId == user.gameUserInfoList[i].SeatId){
                        if (user.gameUserInfoList[i].SeatStatus == SEAT_STATUS.Ready)
                        {
                            int tempIndex = pdk.returnOtherSeatIndex(user.gameUserInfoList[i].SeatId);
                            pdkUsers[tempIndex].ReadyStatus.gameObject.SetActive(true);
                            //隐藏准备 换桌 邀请 按钮
                            gamePDKPanel.PrepareGreenBtn.SetActive(false);
                            gamePDKPanel.ChangeTableOrangeBtn.SetActive(false);
                            gamePDKPanel.FriendRoomObj.SetActive(false);
                            Debug.Log("重连ready");
                        }
                    }
                   
                }
            }
            else if (newpb.RoomInfo.RoomStatus == ROOM_STATUS.Gaming)
            {
                //隐藏准备状态
                for (int i = 0; i < 3; i++)
                {
                    pdkUsers[i].ReadyStatus.gameObject.SetActive(false);
                }
                //隐藏准备 换桌 邀请 按钮
                gamePDKPanel.PrepareGreenBtn.SetActive(false);
                gamePDKPanel.ChangeTableOrangeBtn.SetActive(false);
                gamePDKPanel.FriendRoomObj.SetActive(false);
                //生成cards 显示自己的牌
                List<int> ownCards = newpb.CardList.ToList();
                GameObject pdkCards = NGUITools.AddChild(Root, (GameObject)(Resources.Load(GamePDKPrefabPath.PDKCards)));
                pdkCardsControl = pdkCards.GetComponent<PDKCardsControl>();
                //重连显示手牌
                pdkCardsControl.ReconnectShowCards(ownCards);               
                //显示左右玩家剩余牌
                for (int i = 0; i < user.gameUserInfoList.Count; i++)
                {                  
                    if (user.gameUserInfoList[i].SeatId != pdk.seatId)
                    {
                        pdkCardsControl.OtherCardRemainderShow(user.gameUserInfoList[i].RemainCount, user.gameUserInfoList[i].SeatId);
                        
                    }
                    //判断重连是否显示报单
                    if(user.gameUserInfoList[i].RemainCount == 1){
                        int index = pdk.returnOtherSeatIndex(user.gameUserInfoList[i].SeatId);
                        pdkUsers[index].BaoDan.SetActive(true);
                    }
                }
                
                //List<int> newList = new List<int>();
                //List<GameUserInfo> newUserInfoList = new List<GameUserInfo>();
                //for (int i = 0; i < newpb.UserInfoList.Count; i++)
                //{
                //    if (pdk.seatId == newpb.UserInfoList[i].SeatId)
                //    {
                //        newList = ReSortSeatId();
                //    }
                //}

                //for (int i = 0; i < newList.Count; i++)
                //{
                //    for (int j = 0; j < newpb.UserInfoList.Count; j++)
                //    {
                //        if (newpb.UserInfoList[j].SeatId == newList[i])
                //        {
                //            newUserInfoList.Add(newpb.UserInfoList[j]);
                //        }
                //    }

                //}
                //Debug.Log(newUserInfoList.Count);
                //上家的牌存进去
                for (int i = 0; i < newpb.UserInfoList.Count; i++)
                {                   
                    if (newpb.UserInfoList[i].PokerType != (int)POKER_TYPE.Pass)
                    {
                        pdkCardsControl.lastPokerType = (POKER_TYPE)newpb.UserInfoList[i].PokerType;
                        pdkCardsControl.lastSeatId = newpb.UserInfoList[i].SeatId;
                        pdkCardsControl.lastOutCards = newpb.UserInfoList[i].OutCardList.ToList();
                        Debug.Log(pdk.seatId + "  " + pdkCardsControl.lastSeatId);
                        Debug.Log(newpb.UserInfoList[i].SeatId + "  " + newpb.UserInfoList[i].PokerType + "   " + newpb.UserInfoList[i].OutCardList.Count);
                        //玩家出的牌显示出来
                        pdkCardsControl.ShowPlayerOutCard(newpb.UserInfoList[i].OutCardList.ToList(), newpb.UserInfoList[i].SeatId, (POKER_TYPE)newpb.UserInfoList[i].PokerType, newpb.TurnDetail.SeatId);
                    }
                    Debug.Log("外面：" + newpb.UserInfoList[i].SeatId + "  " + newpb.UserInfoList[i].PokerType + "   " + newpb.UserInfoList[i].OutCardList.Count);                    
                }
               
               
                //判断该谁出牌
                //如果是自己出牌
                int tempIndex = pdk.returnOtherSeatIndex(newpb.TurnDetail.SeatId);
                Debug.Log(pdk.seatId + "  " + newpb.TurnDetail.SeatId);
                if (pdk.seatId == newpb.TurnDetail.SeatId)
                {                    
                    if (newpb.TurnDetail.IsPlay == true)
                    {
                        pdkCardsControl.ShowOutCardButton();
                        //pdkCardsControl.outCardBtnFather.SetActive(true);
                    }
                    else
                    {
                        Debug.Log("重连我不能出牌");
                        RunPlayRequest lg = new Pb.RunPlayRequest { };
                        SocketManager socketManager = SocketManager.Instance;
                        socketManager.SendProtobuf1(lg, MsgId.RunPlayRequest);
                    }
                    
                }
                //显示时钟
                //pdkUsers[tempIndex].clock.SetActive(true);
                //pdkUsers[tempIndex].clock.GetComponent<PDKTimeControl>().timeCount = 26;
                //判断是否托管
                Debug.Log("判断重连是否托管");
                if(newpb.TurnDetail.IsRobot == true){
                    Debug.Log("重连托管");
                    pdkUsers[tempIndex].AutoStatus.SetActive(true);
                    if(newpb.TurnDetail.SeatId == pdk.seatId){
                        Debug.Log("我托管了");
                        pdkCardsControl.CancelAuto.SetActive(true);
                    }
                }
            }
        }
        
    }
    #endregion 重连


    #region  出牌音效

    /// <summary>
    /// 出牌音效
    /// </summary>
    /// <param name="type"></param>
    /// <param name="card"></param>
    /// <param name="seatid"></param>
    private void PlaySound(POKER_TYPE type, int card, int seatid)
    {
        int tempIndex = pdk.returnOtherSeatIndex(seatid);
        SEX sex = SEX.Unknown;
        AudioClip ac = new AudioClip();
        for (int i = 0; i < user.gameUserInfoList.Count; i++)
        {
            if (user.gameUserInfoList[i].SeatId == seatid)
            {
                if (user.gameUserInfoList[i].Sex == SEX.Male)
                {
                    sex = SEX.Male;
                }
                else
                {
                    sex = SEX.Female;
                }
            }
        }
        if (type == POKER_TYPE.Pass)
        {
            if (sex == SEX.Male)
            {
                ac = CommonMen[9];
            }
            else
            {
                ac = CommonWomen[9];
            }
        }
        else if (type == POKER_TYPE.Single)
        {
           
            card = card % 13;
            
            if (sex == SEX.Male)
            {
                ac = cardsSingleMen[card];
            }
            else
            {
                ac = cardsSingleWomen[card];
            }
        }
        else if (type == POKER_TYPE.Twin)
        {
            card = card % 13;
            if (sex == SEX.Male)
            {
                ac = cardsTwinMen[card];
            }
            else
            {
                ac = cardsTwinWomen[card];
            }
        }
        else if (type == POKER_TYPE.Triple)
        {
            card = card % 13;
            if (sex == SEX.Male)
            {
                ac = muchThreeMen[card];
            }
            else
            {
                ac = muchThreeWomen[card];
            }
        }
        else if (type == POKER_TYPE.TripleWithSingle)
        {
            if (sex == SEX.Male)
            {
                ac = CommonMen[3];
            }
            else
            {
                ac = CommonWomen[3];
            }
        }
        else if (type == POKER_TYPE.TripleWithTwin)
        {
            if (sex == SEX.Male)
            {
                ac = CommonMen[4];
            }
            else
            {
                ac = CommonWomen[4];
            }
        }
        else if (type == POKER_TYPE.StraightSingle)
        {
            if (sex == SEX.Male)
            {
                ac = CommonMen[0];
            }
            else
            {
                ac = CommonWomen[0];
            }
            //GameObject Shunzi = NGUITools.AddChild(gameObject, (GameObject)(Resources.Load("GameDDZ/Animation/Shunzi")));
            //if (tempIndex == 0)
            //{
            //    Shunzi.transform.localPosition = new Vector3(-16, -77, 0);
            //}
            //else if (tempIndex == 2)
            //{
            //    Shunzi.transform.localPosition = new Vector3(-197, 170, 0);
            //}
            //else if (tempIndex == 1)
            //{
            //    Shunzi.transform.localPosition = new Vector3(161, 170, 0);
            //}
        }
        else if (type == POKER_TYPE.StraightTwin)
        {
            if (sex == SEX.Male)
            {
                ac = CommonMen[1];
            }
            else
            {
                ac = CommonWomen[1];
            }
            

            //GameObject Liandui = NGUITools.AddChild(gameObject, (GameObject)(Resources.Load("GameDDZ/Animation/Liandui")));
            //Liandui.transform.localScale = new Vector3((float)0.4, (float)0.4, 0);
            //if (tempIndex == 0)
            //{
            //    Liandui.transform.localPosition = new Vector3(-16, -77, 0);
            //}
            //else if (tempIndex == 2)
            //{
            //    Liandui.transform.localPosition = new Vector3(-200, 174, 0);
            //}
            //else if (tempIndex == 1)
            //{
            //    Liandui.transform.localPosition = new Vector3(158, 174, 0);
            //}
        }
        else if (type == POKER_TYPE.FourWithSingle)
        {
            if (sex == SEX.Male)
            {
                ac = CommonMen[5];
            }
            else
            {
                ac = CommonWomen[5];
            }
        }
        else if (type == POKER_TYPE.FourWithTwin)
        {
            if (sex == SEX.Male)
            {
                ac = CommonMen[6];
            }
            else
            {
                ac = CommonWomen[6];
            }
        }
        else if (type == POKER_TYPE.FourBomb)
        {
            if (sex == SEX.Male)
            {
                ac = CommonMen[7];
            }
            else
            {
                ac = CommonWomen[7];
            }
            //SoundModel.PlayEffectBg(effectBg[3]);
            //GameObject Zhadan = NGUITools.AddChild(gameObject, (GameObject)(Resources.Load("GameDDZ/Animation/Zhadan")));
        }      
        else if (type == POKER_TYPE.PlanePure || type == POKER_TYPE.PlaneWithSingle || type == POKER_TYPE.PlaneWithTwin)
        {
            if (sex == SEX.Male)
            {
                ac = CommonMen[2];
            }
            else
            {
                ac = CommonWomen[2];
            }

            //SoundModel.PlayEffectBg(effectBg[4]);
            //GameObject Feiji = NGUITools.AddChild(gameObject, (GameObject)(Resources.Load("GameDDZ/Animation/Feiji")));
            //Feiji.transform.localScale = new Vector3((float)0.4, (float)0.4, 0);
            //if (tempIndex == 0)
            //{
            //    Feiji.transform.localPosition = new Vector3(-16, -77, 0);
            //}
            //else if (tempIndex == 2)
            //{
            //    Feiji.transform.localPosition = new Vector3(-199, 178, 0);
            //}
            //else if (tempIndex == 1)
            //{
            //    Feiji.transform.localPosition = new Vector3(164, 178, 0);
            //}
        }
        SoundModel.PlaySound(ac);
    }
    #endregion  出牌音效

    /// <summary>
    /// 显示第一个出牌的玩家的出牌按钮
    /// </summary>
    /// <returns></returns>
    IEnumerator ShowFirstOutCard(RunRoomBeginNotification newpb)
    {
        yield return new WaitForSeconds(2);
        //确定出牌的玩家
        int tempBankerIndex = pdk.returnOtherSeatIndex(newpb.BankerSid);
        pdkUsers[tempBankerIndex].clock.SetActive(true);
        if (pdk.seatId == newpb.BankerSid)
        {
            //pdkCardsControl.outBtn.SetActive(true);
            //pdkCardsControl.tiShiBtn.SetActive(true);
            pdkCardsControl.outCardBtnFather.SetActive(true);
        } 
    }

    IEnumerator HideOwnPassStatus()
    {
        yield return new WaitForSeconds(1.5f);
        pdkCardsControl.passStatusObjs[0].SetActive(false);
    }   

    /// <summary>
    /// 重新确定玩家列表的顺序
    /// </summary>
    List<int> ReSortSeatId()
    {
        List<int> tempInt = new List<int>();
       
        int downSeat = pdk.seatId;
        int rightSeat = 0;
        int leftSeat = 0;

        if (downSeat == 1)
        {
            downSeat = 1;
            rightSeat = 2;
            leftSeat = 3;
        }
        if (downSeat == 2)
        {
            downSeat = 2;
            rightSeat = 3;
            leftSeat = 1;
        }
        if (downSeat == 3)
        {
            downSeat = 3;
            rightSeat = 1;
            leftSeat = 2;
        }
       
        tempInt.Add(downSeat);
        tempInt.Add(rightSeat);
        tempInt.Add(leftSeat);
        return tempInt;
    }


    /// <summary>
    /// 加载微信头像
    /// </summary>
    /// <param name="texture"></param>
    /// <param name="url"></param>
    /// <returns></returns>
    //IEnumerator GetWWWFace(UITexture texture, string url)
    //{
    //    if (url != "")
    //    {
    //        WWW www = new WWW(url);
    //        yield return www;
    //        if (www.isDone)
    //        {
    //            if (www.error == null)
    //            {

    //            }
    //            texture.mainTexture = www.texture;
    //            texture.gameObject.SetActive(true);
    //        }
    //        else
    //        {

    //        }
    //        www.Dispose();
    //    }
    //}
}
